import datetime
import time


from django.utils.deprecation import MiddlewareMixin
import pymysql

from xuanba_setting.settings import DATABASES


class LogMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.user.id is None:
            return None
        else:
            db = DATABASES['default']
            conn = pymysql.connect(host=db['HOST'],
                                   user=db['USER'],
                                   password=db['PASSWORD'],
                                   database=db['NAME'],
                                   port=db['PORT'],
                                   )
            sql = f'insert user_log (user_id, ip, type, url)'\
                  f'values ({request.user.id} ,"{request.environ.get("REMOTE_ADDR")}",'\
                  f'"{request.META.get("REQUEST_METHOD")}", "{request.path}")'
            with conn.cursor() as cs:
                cs.execute(sql)
            conn.commit()
            conn.close()

        return None

    def process_view(self, request, callback, callback_args, callback_kwargs):
        return None

    def process_template_response(self, request, response):
        return response

    def process_exception(self, request, exception):

        return None

    def process_response(self, request, response):
        return response
